//
//  StreamBuffer.m
//  tcpoctest
//
//  Created by gump on 10/18/12.
//  Copyright (c) 2012 gump. All rights reserved.
//

#import "StreamBuffer.h"

@implementation StreamBuffer

-(void)dealloc
{
    free(streamDate);
}

-(id)init
{
    self = [super init];
    if (self)
    {
        writePoint = 0;
        readPoint = 0;
        length = 0;
        mReadValue = 0;
        streamDate = (unsigned char *)malloc(STREAM_LENGTH);
        assert(streamDate != nil);
    }
    
    return self;
}

-(void)Write:(unsigned char*)date withSize:(int)size
{
    memcpy(streamDate + writePoint, date, size);
    writePoint += size;
    length += size;
}

-(bool)ReadHead
{
    memcpy(&mReadValue, streamDate + readPoint, HEAD_LENGTH);
    mReadValue = ntohl(mReadValue);
    
    if(length <= 0 || length < mReadValue)
    {
        return false;
    }
    
    return true;
}

-(bool)Read
{
    if(length <= 0)
    {
        return false;
    }
    
    memcpy(&mReadValue, streamDate + readPoint, HEAD_LENGTH);
    mReadValue = ntohl(mReadValue);
    
    readPoint += HEAD_LENGTH;
    length -= HEAD_LENGTH;
    return true;
}

-(bool)Read:(unsigned char *)date withLength:(int)len
{
    if(len > length)
    {
        return false;
    }
    
    memcpy(date, streamDate + readPoint, len);
    readPoint += len;
    length -= len;
    return true;
}

-(int)getStreamSize
{
    return length;
}

-(void)reSet
{
    if(length > 0)
    {
        memcpy(streamDate, streamDate + readPoint,length);
        readPoint = 0;
        writePoint = length;
    }
    else
    {
        readPoint = 0;
        writePoint = 0;
        length = 0;
    }
}

-(void)Clean
{
    writePoint = 0;
    readPoint = 0;
    length = 0;
    mReadValue = 0;
    
    memset(streamDate, 0, STREAM_LENGTH);
}

-(int)getReadValue
{
    return mReadValue;
}

@end
